package com.GlobalPaint.app.ui.HTML;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.ui.Login.Login;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.blankj.utilcode.utils.SPUtils;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebHistoryItem;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class CommonHTML extends AppCompatActivity {
    private WebView wb_commom;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_html);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);

            getWindow().setFormat(PixelFormat.TRANSLUCENT);  //（这个对宿主没什么影响，建议声明）
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }

        wb_commom = (WebView) findViewById(R.id.wb_commom);
        progressDialog = CommUtility.openProgressDialog(CommonHTML.this,
                progressDialog, "正在加载中...");
        wb_commom.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {

                if (url.equals("phone://outofdate")) {
                    SPUtils spUtils = new SPUtils(DataManager.context, "login");
                    spUtils.remove("user");
                    //退出时清除缓存
                    DataManager.lruCache = new LruCache<>(10);
                    Intent intent = new Intent(CommonHTML.this, Login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //判断url拦截事件
                if (url.indexOf("append")!=-1) {
                    finish();
                    wb_commom.clearHistory(); // 清除
                    return true;
                } else if (url.indexOf("appLoginOut")!=-1) {
                    SPUtils spUtils = new SPUtils(DataManager.context, "login");
                    spUtils.remove("user");
                    //退出时清除缓存
                    DataManager.lruCache = new LruCache<>(10);
                    Intent intent = new Intent(CommonHTML.this, Login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                    return true;
                }  else if(url.indexOf("addNewTuJi")!=-1) {

                    String[] list = url.split("=");//逗号以后为数组；
                   String id= list[1];
                    Intent intent=new Intent(CommonHTML.this,PutPictureActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                    return true;

                }  else if(url.indexOf("addNewArticle!")!=-1) {

                    String[] list = url.split("!");//逗号以后为数组；
                    String id= list[1];
                    Intent intent=new Intent(CommonHTML.this,PutWenzhangActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                    return true;

                }
                else if(url.indexOf("largeImage")!=-1){

                    String[] list1 = url.split("!");//逗号以后为数组；
                    String url12= list1[1];
                    Intent intent=new Intent(CommonHTML.this,tupianxqActivity.class);
                    intent.putExtra("uri",url12);
                    startActivity(intent);
                    return true;
                }
                else if(url.indexOf("share")!=-1) {
                  String url2 =Constants.JASON_SERVICE_URL_SHARE; //替换路径 分享路径
                    String[] list1 = url.split("!");//逗号以后为数组；
                    String zixunId= list1[1];
                    String title= list1[2];
                    try {
                        title = URLDecoder.decode(URLDecoder.decode(title, "utf-8"), "utf-8");
                    }catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    String url12=url2+zixunId;
                    Log.d("dddd", "url12: "+url12);

                    UMWeb web = new UMWeb(url12);
                    web.setTitle("漆联天下");//标题
                    web.setDescription(title);//描述
                    new ShareAction(CommonHTML.this)
                            .withMedia(web)
                            .setDisplayList(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN)
                            .setCallback(umShareListener).open();
                    return true;
                }else if(url.indexOf("imageShare")!=-1) {
                    String[] list1 = url.split("!");//逗号以后为数组；
                    String id= list1[1];
                    String title= list1[2];
                    try {
                        title = URLDecoder.decode(URLDecoder.decode(title, "utf-8"), "utf-8");
                    }catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    UMWeb web = new UMWeb("http://"+id);
                    web.setTitle("漆联天下");//标题
                    web.setDescription(title);//描述
                    new ShareAction(CommonHTML.this)
                            .withMedia(web)
                            .setDisplayList(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN)
                            .setCallback(umShareListener).open();
                    return true;
                }else if(url.indexOf("videoShare")!=-1) {
                    String[] list1 = url.split("!");//逗号以后为数组；
                    String id= list1[1];
                    String title= list1[2];
                    try {
                        title = URLDecoder.decode(URLDecoder.decode(title, "utf-8"), "utf-8");
                    }catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    UMWeb web = new UMWeb("http://"+id);
                    web.setTitle("漆联天下");//标题
                    web.setDescription(title);//描述
                    new ShareAction(CommonHTML.this)
                            .withMedia(web)
                            .setDisplayList(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN)
                            .setCallback(umShareListener).open();
                    return true;
                }else {
                    CommUtility.closeProgressDialog(progressDialog);
                    wb_commom.loadUrl(url);
                    return false;
                }
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                CommUtility.closeProgressDialog(progressDialog);
            }

            //接收不到404
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                CommUtility.closeProgressDialog(progressDialog);
            }
        });

        WebSettings webSettings = wb_commom.getSettings();
        webSettings.setJavaScriptEnabled(true);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        if(DataManager.typeId==180){
            wb_commom.loadUrl(Constants.JASON_SERVICE_URL_H5 +"sy_jiShuXueYuan.html?fNodeId="+DataManager.typeId +
                    "&token="+DataManager.userEntity.getCookie()+"&useId="
                    +DataManager.userEntity.getUserId()+"&useName="+DataManager.userEntity.getUserName());
        }else if(DataManager.typeId==150){
            wb_commom.loadUrl(Constants.JASON_SERVICE_URL_H5 +"sy_tuiGuang.html?fNodeId="+DataManager.typeId +
                    "&token="+DataManager.userEntity.getCookie()+"&useId="
                    +DataManager.userEntity.getUserId()+"&useName="+DataManager.userEntity.getUserName());
        }else {
            wb_commom.loadUrl(Constants.JASON_SERVICE_URL_H5 +"sy_sbyp.html?fNodeId="+DataManager.typeId +
                    "&token="+DataManager.userEntity.getCookie()+"&useId="
                    +DataManager.userEntity.getUserId()+"&useName="+DataManager.userEntity.getUserName());
        }

       // wb_commom.loadUrl("http://192.168.1.101:8080"+"/sy_sbyp.html?fNodeId="+DataManager.typeId);
    }



    private boolean canGoBack() {
        if (wb_commom.canGoBack()) {
            WebBackForwardList list = wb_commom.copyBackForwardList();
            WebHistoryItem item = list.getCurrentItem();
            System.out.println("URL: " + item.getUrl());

            if (item.getUrl().indexOf("succeed.html") >= 0) {
                finish();
                return false;
            }else if(item.getUrl().indexOf("MyLeaveDetail.html") >= 0){
                finish();
                return false;
            }
            return wb_commom.canGoBack();

        }
        finish();
        return wb_commom.canGoBack();
    }
    // Prevent the back-button from closing the app
    @Override
    public void onBackPressed() {
        if(canGoBack()) {
            wb_commom.goBack();
        } else {
            //super.onBackPressed();
            exit();
            wb_commom.clearHistory(); // 清除
        }
    }

    private long mExitTime;
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            //     Toast.makeText(AskForLeaveActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }
    //分享回调
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

            //分享开始的回调
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {


            Toast.makeText(CommonHTML.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(CommonHTML.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {

            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(CommonHTML.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {


    }
}
